package test.app.dao.hibernate;

import java.io.Serializable;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Criteria;
import org.hibernate.criterion.Criterion;
import org.springframework.orm.ObjectRetrievalFailureException;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import test.app.dao.GenericDao;

@SuppressWarnings("unchecked")
public class GenericDaoHibernate<T, PK extends Serializable> extends HibernateDaoSupport implements GenericDao<T, PK> {

	protected final Log log = LogFactory.getLog(getClass());
	
	private Class<T> persistentClass;
		
	 public GenericDaoHibernate(Class<T> persistentClass) {
	        this.persistentClass = persistentClass;
	   }
	
	public Class<T> getPersistentClass() {
		return persistentClass;
	}
			
	public T findById(PK id) {
		T entity = (T) super.getHibernateTemplate().get(this.persistentClass, id);
		
		if(entity == null){
			log.warn("Warn--->, " + this.persistentClass + "' Objeto con id '" + id + "' no encontrado...");
            throw new ObjectRetrievalFailureException(this.persistentClass, id);
        }
					
		return entity;
				
	}

	
	public List<T> getAll() {
		
		return super.getHibernateTemplate().loadAll(this.persistentClass);
	}

	
	public T save(T object) {
		return (T)super.getHibernateTemplate().save(object);
		
	}

	public void remove(PK id) {
		super.getHibernateTemplate().delete(this.findById(id));
		
	}

	public void update(T transientObject) {
		super.getHibernateTemplate().update(transientObject);
		
		
	}
	
	
	public List<T> findByCriteria(Criterion... criterion) {
		
		Criteria crit = super.getSession().createCriteria(getPersistentClass());

		for (Criterion c : criterion) {
			crit.add(c);
		}
		
		return crit.list();
	}
	
	

}
